package com.jb.web.application.event;

import com.jb.web.application.RootContainer;
import com.jb.web.bean.BeanFactory;
import com.jb.web.bean.FloatPanel;
import com.jb.web.bean.Panel;
import com.jb.web.bean.Form;

import com.jb.web.bean.Image;
import com.jb.web.bean.Page;
import com.jb.web.bean.UIComponentImpl; 
import com.jb.web.bean.event.UIEvent;
import com.jb.web.context.WebContext;


public class PageEH {
    public void onSaveAs(WebContext ctx, UIEvent event) {
        UIComponentImpl form = (UIComponentImpl)event.getSource();

        try {
            if (!ctx.getSession().isAuthenticated()) {
                ctx.addErrorMessage(form, ctx.getResource("saveNotAllowed"));
                ctx.renderResponse();
                return;
            }

            saveAs(ctx, event);
        } catch (Exception e) {
            ctx.addErrorMessage(form, "Failed to Save");
            ctx.renderResponse();
        }
        return;
    }

    public void onSave(WebContext ctx, UIEvent event) {
        UIComponentImpl form = (UIComponentImpl)event.getSource();

        try {
            if (!ctx.getSession().isAuthenticated()) {
                ctx.addErrorMessage(form, 
                                     (String)ctx.getResource("saveNotAllowed"));
                return;
            }
            String regionName = ctx.getPageName();
            Page page = ctx.getSession().getPage(ctx, regionName, false);
            if (page != null) {
                String userName = ctx.getSession().getUser().getUserName();
                if (userName.equals(page.getCreatedBy())) {
                    page.save(ctx);
                } else {
                    ctx.addErrorMessage(form, ctx.getResource("saveNotAllowed", new String[] { page.getApplication() }));
                    return;
                }
            }
        } catch (Exception e) {
            ctx.addErrorMessage(form, "Failed to Save");
        }

        return;
    }
    
    private Panel newPanel(WebContext ctx, UIComponentImpl parent) {
        return (Panel)BeanFactory.addNewComponent(ctx, parent, Panel.class.getName());
    }
     
    public void onCreatePage(WebContext ctx, UIEvent event) {
        if (!ctx.getSession().isAuthenticated()) {
            ctx.addErrorMessage(this, "Function is only available for signed in users");
        }

        String pageName = event.getParameter("pageName");

        if (pageName.toLowerCase().endsWith(".xsp")) {
            pageName = pageName.substring(pageName.length() - 4);
        }
        //only if same name within same application is counted as duplicate
        if (!testPage(ctx, pageName)) {
            ctx.renderResponse();
            return;
        } 
        
        String templateId = event.getParameter("templateId");
        Page page = null;
        page = RootContainer.createPage(ctx, pageName);
        page.setAccess("public");
        page.setCreatedBy(ctx.getSession().getUser().getId());
        page.setDefault(ctx);
        page.setCreatedAt(System.currentTimeMillis());
        page.setDesignable(true);
        page.setApplication(ctx.getApplicationName());
        page.setBorderStyle("margin:0px;");
        page.setOverFlow("hidden");
        page.setHeight("");

        if ("1".equals(templateId)) {
            Panel panel = newPanel(ctx, page);
            panel.setHeight("50px");
            panel.setBackgroundStyle("background-color: silver;");
            panel.setValue("top");
            panel.setStyleClass("jb_top_banner");
            panel.setSequence(0);
            
            panel = newPanel(ctx, page);
            panel.setHeight("190px");
            panel.setStretch("vertical");
            panel.setSequence(1);
            panel.setValue("middle");
            
            Panel left = newPanel(ctx, panel);
            
            left.setValue("left");
            left.setHeight("100%");
            left.setWidth("200px");
            left.setSequence(1);
            left.setBackgroundStyle("background-color: #cFcFcF;");
            left.setFloatStyle("left");

            FloatPanel splitter = new FloatPanel();
            panel.addChild(splitter);
            splitter.setStyleClass("jb_splitter");
            splitter.setSequence(2);
            splitter.setDraggable(true);
            splitter.setDragWithin(panel.getClientId());
            splitter.setCloneOnDrag(true);

            Image img=new Image();
            img.setLocation("resources/images/windows/Back.gif");
            img.setOnClick("JB.splitterImages('"+img.getClientId()+"','"+left.getClientId()+"');");
            img.setBorderStyle("position:relative;top:95%;left:-6px;");
            img.setCursor("default");
            splitter.addChild(img);
            
            Panel right = newPanel(ctx, panel);
            right.setFloatStyle("right");
            right.setValue("right");
            right.setHeight("100%");
            right.setWidth("200px");
            right.setStretch("horizontal");
            right.setSequence(2);
            right.setBackgroundStyle("background-color: #ffff55;");
            splitter.setOnMouseUp("JB.splitterMoved('"+splitter.getClientId()+"', '"+left.getClientId()+"', '"+right.getClientId()+"', '"
                                  +panel.getClientId()+"', 'horizontal');");
            
            panel = newPanel(ctx, page);
            panel.setHeight("20px");
            panel.setSequence(3);
            panel.setValue("status");
        } else if ("2".equals(templateId)) {
            Panel panel = newPanel(ctx, page);
            panel.setHeight("50px");
            panel.setBackgroundStyle("background-color: #ffff55;");
            panel.setValue("top");
            panel.setStyleClass("jb_top_banner");
            panel.setSequence(0);
            
            panel = newPanel(ctx, page);
            panel.setHeight("190px");
            panel.setStretch("vertical");
            panel.setSequence(1);
            panel.setValue("middel");
            
            Panel left = newPanel(ctx, panel);
            
            left.setValue("left");
            left.setHeight("100%");
            left.setWidth("200px");
            left.setSequence(1);
            left.setBackgroundStyle("background-color: #cFcFcF;");
            left.setFloatStyle("left");
            
            FloatPanel splitter = new FloatPanel();
            panel.addChild(splitter);
                //newPanel(ctx, panel);
            splitter.setStyleClass("jb_splitter");
            splitter.setSequence(2);
            splitter.setDraggable(true);
            splitter.setDragWithin(panel.getClientId());
            splitter.setCloneOnDrag(true);

            Image img=new Image();
            img.setLocation("resources/images/windows/Back.gif");
            img.setOnClick("JB.splitterImages('"+img.getClientId()+"','"+left.getClientId()+"');");
            img.setBorderStyle("position:relative;top:95%;left:-6px;");
            img.setCursor("default");
            splitter.addChild(img);
            
            //Element.toggle('leftPane');JBStretchBody();
            Panel middle = newPanel(ctx, panel);
            middle.setFloatStyle("left");
            middle.setValue("middle");
            middle.setHeight("100%");

            middle.setStretch("horizontal");
            middle.setSequence(3);
            middle.setBackgroundStyle("background-color: #ffffee;");
            splitter.setOnMouseUp("JB.splitterMoved('"+splitter.getClientId()+"', '"+left.getClientId()+"', '"+middle.getClientId()+"', '"
                                  +panel.getClientId()+"', 'horizontal');");
            
            left = newPanel(ctx, middle);
            left.setFloatStyle("left");
            left.setValue("left");
            left.setHeight("100%");
            left.setWidth("200px");
            left.setStretch("horizontal");
            left.setSequence(1);
            left.setBackgroundStyle("background-color: #ffff55;");
     //       middle.addChild(left);

            splitter = new FloatPanel();
            middle.addChild(splitter);
            splitter.setStyleClass("jb_splitter");
            splitter.setSequence(2);
            splitter.setDraggable(true);
            splitter.setDragWithin(panel.getClientId());
            splitter.setCloneOnDrag(true);
            splitter.setBackgroundStyle("background-color: #ffff33;");
            
            Panel right = newPanel(ctx, middle);
            right.setFloatStyle("left");
            right.setValue("right");
            right.setHeight("100%");
            right.setWidth("200px");
            right.setSequence(3);
            right.setBackgroundStyle("background-color: #22ff55;");

            img=new Image();
            img.setLocation("resources/images/windows/Next.gif");
            img.setOnClick("JB.splitterImages('"+img.getClientId()+"','"+right.getClientId()+"');");
            img.setBorderStyle("position:relative;top:95%;left:-6px;");
            img.setCursor("default");
            splitter.addChild(img);            

            splitter.setOnMouseUp("JB.splitterMoved('"+splitter.getClientId()+"', '"+left.getClientId()+"', '"+right.getClientId()+"', '"
                                  +middle.getClientId()+"', 'horizontal');");
            
            panel = newPanel(ctx, page);
            panel.setHeight("20px");
            panel.setSequence(6);
            panel.setValue("status");
        } else if ("3".equals(templateId)) {
            Panel panel = newPanel(ctx, page);
            page.setOverFlow("hidden");
            panel.setHeight("60px");
            panel.setValue("");
            panel.setSequence(0);
            Panel t1 = newPanel(ctx, panel);
            t1.setHeight("18px");
            t1.setStyleClass("jb_window_title");
            Panel t2 = newPanel(ctx, panel);
            t2.setStyleClass("jb_top_banner");
            t2.setStretch("vertical");
            
            panel = newPanel(ctx, page);
            panel.setHeight("190px");
            panel.setStretch("vertical");
            panel.setSequence(1);
            panel.setValue("middel");
            
            Panel left = newPanel(ctx, panel);
            
            left.setValue("left");
            left.setHeight("100%");
            left.setWidth("200px");
            left.setSequence(1);
            left.setBackgroundStyle("background-color: #cFcFcF;");
            left.setFloatStyle("left");
            
            FloatPanel splitter = new FloatPanel();
            panel.addChild(splitter);
            splitter.setStyleClass("jb_splitter");
            splitter.setSequence(2);
            splitter.setDraggable(true);
            splitter.setDragWithin(panel.getClientId());
            splitter.setCloneOnDrag(true);

            Image img=new Image();
            img.setLocation("resources/images/windows/Back.gif");
            img.setCursor("default");
            img.setOnClick("JB.splitterImages('"+img.getClientId()+"','"+left.getClientId()+"');");
    //        img.setOnClick("Element.toggle('"+left.getClientId()+"');JBStretchBody()");
            img.setBorderStyle("position:relative;top:95%;left:-6px;");
            splitter.addChild(img);

            Panel right = newPanel(ctx, panel);
            right.setFloatStyle("right");
            right.setValue("right");
            right.setHeight("100%");
            right.setWidth("200px");
            right.setStretch("horizontal");
            right.setSequence(2);
            right.setBackgroundStyle("background-color: #44ff55;");
            splitter.setOnMouseUp("JB.splitterMoved('"+splitter.getClientId()+"', '"+left.getClientId()+"', '"+right.getClientId()+"', '"
                                  +panel.getClientId()+"', 'horizontal');");
            
            panel = newPanel(ctx, page);
            panel.setHeight("20px");
            panel.setSequence(3);
            panel.setValue("status");
        } else if ("4".equals(templateId)) {
            page.setBackgroundStyle("background-image:url(resources/images/bg/bg.png);background-position:top center;background-repeat:repeat-y;");

            page.setAlign("center");
            Panel panel =  newPanel(ctx, page);
            panel.setHeight("20px");
            panel.setBackgroundStyle("background-color: silver;");
            panel.setWidth("620px");
            panel =  newPanel(ctx, page);
            panel.setWidth("620px");
        } else if ("5".equals(templateId)) {
            //nothing here
        }

        if ((ctx.getSession().getUser() != null)) {
            page.setCreatedBy(ctx.getSession().getUser().getId());
            page.save(ctx);
            ctx.setRedirectPage(pageName + ".xsp");
        }
        
    }

    public void onDeletePage(WebContext ctx, UIEvent event) {
        String pageName = event.getParameter("pageName");

        if (pageName != null) {
            if (pageName.endsWith(".xsp")) {
                pageName = pageName.substring(0, pageName.length() - 4);
            }

            Page page = ctx.getSession().getPage(ctx,pageName, false);

            if (page != null) {
                if (page.getCreatedBy().equals(ctx.getSession().getUser().getId())) {
                    page.delete(ctx);
                    ctx.getSession().removeCachedPage(page);
                } else {
                    ctx.addErrorMessage(page, "Can not delete page not owned by you");
                }
            } else {
                ctx.addErrorMessage(this, "Page not found");
            }
        }
    }

    public void onSelectItem(WebContext ctx, UIEvent event) {
        ctx.getSession().setSelected((UIComponentImpl)event.getSource());
    }
    
    private boolean testPage(WebContext ctx, String pageName) {
        if(ctx==null||ctx.getSession()==null)
            return false;
        Page newpage = ctx.getSession().getPage(ctx, pageName, false);
            if ((newpage != null) && 
                ctx.getApplicationName().equalsIgnoreCase(newpage.getApplication())) {
                ctx.addErrorMessage(this, 
                                     "Page <a href=\"" + ctx.formURL(pageName, 
                                                                      newpage) + 
                                     "\">" + pageName + "</a> already exist!");
                
                return false;
            }   
            return true;
    }
    
    private boolean saveAs(WebContext ctx, UIEvent event) {
        String newName = event.getParameter("name");
        String pageName = event.getParameter("pageName");

        if ((pageName == null) || (pageName.length() == 0)) {
            ctx.addErrorMessage(this, "Save as must have a pageName");
            ctx.renderResponse();
            return false;
        }
        if ((newName == null) || (newName.length() == 0)) {
            ctx.addErrorMessage(this, "Save as must have a name");
            ctx.renderResponse();
            return false;
        }
        
        if(!testPage(ctx, newName)) {
            ctx.renderResponse();
            return false;
        }
        
        Page page = ctx.getSession().getPage(ctx, pageName, false);

        if (page != null) {
            Page saveAsComp = (Page)page.clone(ctx, true, false);

            saveAsComp.setId(newName);
            saveAsComp.setCreatedBy(ctx.getSession().getUser().getUserName());
            saveAsComp.setApplication(ctx.getSession().getApplicationName());

            try {
                saveAsComp.save(ctx);
                Form form = (Form)event.getSource();
                //goto newly created page
                ctx.getSession().setSelected(null);
                form.setActionForwards(newName+".xsp");
            } catch (Exception e) {
                ctx.addErrorMessage(saveAsComp, "Save as failed due to" + e.toString());
                ctx.renderResponse();
            }
            return true;
        } else
        {
            ctx.addErrorMessage(ctx, "Save as failed to save - page not found");
            ctx.renderResponse();
            return false;
        }
    }
}
